package org.dusin.weijiwufang.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.List;
import org.apache.log4j.Logger;
import org.dusin.weijiwufang.bo.StatusBean;

import org.dusin.weijiwufang.dao.StatusDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;


/**
 * 在JavaDB数据库上的实现
 * @author dusin
 */
public class StatusDaoImpl implements StatusDao {

    static Logger logger = Logger.getLogger(StatusDaoImpl.class);
    private JdbcTemplate jdbcTemplate;
    public int size;

    public StatusDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public boolean doCreate(StatusBean bean) {
        boolean flag = true;
        String sql = null;
        sql = "INSERT INTO status(name,note)"
                + " VALUES (?,?)";
        jdbcTemplate.update(sql,
                    bean.getName(),
                    bean.getNote()
                );
        return flag;
    }

    @Override
    public StatusBean findById(long id){
        String sql = "SELECT id,name,note FROM status where id=?";
        return this.jdbcTemplate.queryForObject(sql,new Object[]{id}
                ,new StatusBeanMapper());
    }
    
   
    @Override
    public List<StatusBean> findAll() {        
        String sql = "SELECT id,name,note FROM status";
        return this.jdbcTemplate.query( sql, new StatusBeanMapper());      
    }

    @Override
    public boolean doUpdate(StatusBean bean) {
        String sql = "update status set name=?,note=? where id = ?";
        this.jdbcTemplate.update(sql,bean.getName()
                ,bean.getNote()
                ,bean.getId());
        return true;       
    }

    @Override
    public boolean doDeleteById(long id) {
        String sql  = "delete from status where id=?";
        this.jdbcTemplate.update(sql,id);
        return true;
    }
    
    
    
    private static final class StatusBeanMapper implements RowMapper<StatusBean> {
        
        @Override
        public StatusBean mapRow(ResultSet rs, int rowNum) throws SQLException {
            StatusBean bean = new StatusBean();            
            bean.setId(rs.getLong("id"));
            bean.setName(rs.getString("name"));           
            bean.setNote(rs.getString("note"));           
            return bean;
        }
    }
    
    
}
